//
//  CYVisitorLoginView.swift
//  CYWeibo
//
//  Created by 媛 on 16/5/22.
//  Copyright © 2016年 yuan. All rights reserved.
//

import UIKit
//导入命名空间
import SnapKit

//MARK: I.声明代理协议
// NSObjectProtocol 继承基协议  可以使用weak 关键字
@objc protocol CYVisitorLoginViewDelegate: NSObjectProtocol {

    //声明协议方法
    //optional 可选方法
    optional func userWillLogin()
    func userWillRegister()
    
}


class CYVisitorLoginView: UIView {

    //MARK: II.声明代理属性
    weak var visitorDelegate: CYVisitorLoginViewDelegate?
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    //默认实现报错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 通过外界调用，设置访客视图页面中心显示的图片
    func updateUI(title: String, imageName: String,isHome: Bool = false) {
        
        if  isHome {
            //是首页  做动画
            startAnimation()
        } else {
            //不是首页
            largeHouse.hidden = true
            //将圈圈移到最顶层
            bringSubviewToFront(circleImg)
        }
        circleImg.image = UIImage(named: imageName)
        tipLabel.text = title
    }
    
    //给圈圈添加动画效果
    private func startAnimation() {
        let basic = CABasicAnimation(keyPath: "transform.rotation")
        //动画时间
        basic.duration = 15
        //动画的重复次数
        basic.repeatCount = MAXFLOAT
        //转动到2PI
        basic.toValue = 2 * M_PI
        //当动画结束 或者 视图处于非活跃状态时，动画效果不移除图层
        basic.removedOnCompletion = false
        //给图层添加动画效果
        circleImg.layer.addAnimation(basic, forKey: nil)
    }

    
    //MARK: 设置UI界面，自动布局
   private func setupUI() {
    
    addSubview(circleImg)
    addSubview(backIcon)
    addSubview(largeHouse)
    addSubview(tipLabel)
    addSubview(loginBtn)
    addSubview(registerBtn)
    
    //MARK: 1、使用系统自动布局类设置约束
    /* NSLayoutConstraint 自动布局的类型
          1.item    需要添加约束的对象
          2.attribute  需要添加的约束的属性
          3.relatedBy   参照的方式 一般使用 精准约束 Equal
          4.toItem       参照的视图  一般参照 父视图 或者 兄弟视图
          5.attribute    参照布局的属性
          6.multiplier   乘积系数，一般使用 1，但是不能使用 0
          7.constant     尺寸: 设置大小  坐标: 偏移  
       约束应该添加到父视图
       公式: view1.attr1 = view2.attr2 * multiplier + constant
     */
    
    //如果使用手写添加约束，需要手动关闭 frame 布局，否则View还是会按照以往的autoresizingMask进行计算
    /*
    circleImg.translatesAutoresizingMaskIntoConstraints = false
    self.addConstraint (NSLayoutConstraint(item: circleImg, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant:  0))
    self.addConstraint (NSLayoutConstraint(item: circleImg, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
    */
    
    //MARK: 2、使用VFL布局方式，可视化布局语言，字符串格式的布局方式
    /*
    tipLabel.translatesAutoresizingMaskIntoConstraints = false
    //垂直方向，相对circleImg
    self.addConstraints (NSLayoutConstraint.constraintsWithVisualFormat("V:[circle]-(16)-[tipLabel]", options: [], metrics: nil, views: ["circle": circleImg, "tipLabel": tipLabel]))
    self.addConstraints (NSLayoutConstraint.constraintsWithVisualFormat("|-[tipLabel]-|", options: .AlignAllCenterX, metrics: nil, views: ["tipLabel": tipLabel]))
    */
    
    //MARK: 3、使用第三方框架SnapKit
    circleImg.snp_makeConstraints { (make) in
        //make 就是circleIcon 取消了frame布局的对象
        make.centerX.equalTo(self.snp_centerX)
        make.centerY.equalTo(self.snp_centerY).offset(-80)
    }
    
    largeHouse.snp_makeConstraints { (make) in
        //            make.centerY.equalTo(circleIcon.snp_centerY)
        //            make.centerX.equalTo(circleIcon.snp_centerX)
        make.center.equalTo(circleImg.snp_center)
    }
    
    //提示文案
    tipLabel.snp_makeConstraints { (make) in
        make.top.equalTo(circleImg.snp_bottom).offset(16)
        make.centerX.equalTo(circleImg.snp_centerX)
        //约束宽度
        make.width.equalTo(230)
        //约束高度，解决切换页面时 按钮位置不一致 导致的跳动
        make.height.equalTo(40)
    }
    
    loginBtn.snp_makeConstraints { (make) in
        make.left.equalTo(tipLabel.snp_left)
        make.top.equalTo(tipLabel.snp_bottom).offset(16)
        make.width.equalTo(100)
        
    }
    
    registerBtn.snp_makeConstraints { (make) in
        make.right.equalTo(tipLabel.snp_right)
        make.top.equalTo(tipLabel.snp_bottom).offset(16)
        make.width.equalTo(100)
    }
    
    backIcon.snp_makeConstraints { (make) in
        make.center.equalTo(circleImg.snp_center)
    }
    
    //一般使用sRGB取值
    let value: CGFloat = 237.0 / 255.0
    //设置访客视图背景色
    backgroundColor = UIColor(red: value, green: value, blue: value, alpha: 1)
    
    
    //添加按钮的点击事件
    loginBtn.addTarget(self, action: #selector(loginBtnClick), forControlEvents: .TouchUpInside)
    
    registerBtn.addTarget(self, action: #selector(registerBtnClick), forControlEvents: .TouchUpInside)
    
    }
    
    
    //MARK: 按钮点击事件
    @objc private func loginBtnClick() {
    
        //MARK: III.使用代理属性，调用协议方法
        //visitorDelegate? 判断代理对象是否为空
        //userWillLogin? 是否响应协议方法
        visitorDelegate?.userWillLogin?()
    }
    
    @objc private func registerBtnClick() {
        
        visitorDelegate?.userWillRegister()
    }
    
    
    //MARK: 懒加载子视图
    //遮罩图片
    private lazy var backIcon: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
    //大圆圈
    private lazy var circleImg: UIImageView = UIImageView(image: UIImage(named:"visitordiscover_feed_image_smallicon"))
    //大房子
    private lazy var largeHouse: UIImageView = UIImageView(image: UIImage(named:"visitordiscover_feed_image_house"))
    
    //提示用户登陆注册的label（文案）
    private lazy var tipLabel: UILabel = {
    
        let lbl = UILabel()
        
        lbl.text = "关注一些人，回到这里看看有什么惊喜"
        lbl.textColor = UIColor.darkGrayColor()
        lbl.font = UIFont.systemFontOfSize(14)
        lbl.textAlignment = .Center
        lbl.numberOfLines = 0
        //最大布局宽度
//        lbl.preferredMaxLayoutWidth = 230
        
        lbl.sizeToFit()
        return lbl
    }()
    
    //登陆注册按钮
    private lazy var loginBtn: UIButton = {
    
        let btn = UIButton()
        
        btn.setTitle("登陆", forState: .Normal)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        //设置图片
        let image = UIImage(named: "common_button_white_disable")!
        let capW = Int(image.size.width * 0.5)
        let capH = Int(image.size.height * 0.5)
        //设置拉伸图片为背景，stretchable：可拉伸的 
        btn.setBackgroundImage(image.stretchableImageWithLeftCapWidth(capW, topCapHeight: capH), forState: .Normal)
        
        return btn
    }()
    
    private lazy var registerBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("注册", forState: .Normal)
        btn.setTitleColor(UIColor.orangeColor(), forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        btn.setBackgroundImage(UIImage(named:"common_button_white_disable"), forState: .Normal)
        
        return btn
    }()

    
   
}
